<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      :ok-loading="modalLoad"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol>
              <AFormItem field="supplierName" label="选中的生产计划">
                <ATable :data="checkData" :pagination="false" :bordered="{ cell: true }">
                  <template #columns>
                    <ATableColumn title="生产计划单" data-index="prodPlanCode" :width="150">
                    </ATableColumn>
                    <ATableColumn title="产品名称" data-index="productName" :width="200">
                    </ATableColumn>
                    <ATableColumn title="规格" data-index="specModel" :width="200"> </ATableColumn>
                    <ATableColumn title="单位" data-index="unit" :width="100"> </ATableColumn>
                  </template>
                </ATable>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="materialQty" label="原材料数量">
                <AInputNumber
                  v-model="form.materialQty"
                  model-event="input"
                  placeholder="原材料数量"
                  hide-button
                  :precision="0"
                  :step="1"
                ></AInputNumber>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="inbounderld" label="入库人员">
                <ASelect v-model="form.inbounderld" placeholder="入库人员" allow-search allow-clear>
                  <AOption
                    v-for="(item, index) in employeeList"
                    :key="index"
                    :label="item.employeeName"
                    :value="item.employeeId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="productQty" label="成品数量">
                <AInputNumber
                  v-model="form.productQty"
                  model-event="input"
                  placeholder="成品数量"
                  hide-button
                  :precision="0"
                  :step="1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="totalLossRate" label="总损耗率">
                <AInputNumber
                  v-model="form.totalLossRate"
                  model-event="input"
                  placeholder="总损耗率"
                  hide-button
                  :precision="1"
                  :step="0.1"
                >
                  <template #suffix> % </template>
                </AInputNumber>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" />
              </AFormItem>
            </ACol>
          </ARow>
          <ACard
            v-for="(item, index) in form.detailList"
            :key="index"
            class="card-container"
            size="small"
          >
            <template #extra>
              <ALink @click="editProduct('add')">增加工序</ALink>
              <ALink v-if="form.detailList.length > 1" @click="editProduct('del', index)">
                删除工序
              </ALink>
            </template>
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem
                  label="工序名称"
                  :field="`detailList[${index}].processId`"
                  :rules="[{ required: true, message: '请选择工序名称' }]"
                  :validate-trigger="['change', 'input', 'blur']"
                >
                  <ASelect
                    v-model="item.processId"
                    allow-search
                    placeholder="输入工序名称搜索"
                    @change="formEvent('processId', item)"
                  >
                    <AOption
                      v-for="(stockItem, index) in processList"
                      :key="index"
                      :label="stockItem.processName"
                      :value="stockItem.processId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="qty" label="工序数量">
                  <AInputNumber
                    v-model="item.qty"
                    model-event="input"
                    placeholder="数量"
                    hide-button
                    :precision="0"
                    :step="1"
                  />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="lossRate" label="损耗率">
                  <AInputNumber
                    v-model="item.lossRate"
                    model-event="input"
                    placeholder="损耗率"
                    hide-button
                    :precision="1"
                    :step="0.1"
                  >
                    <template #suffix> % </template>
                  </AInputNumber>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="mainDirectorId" label="机长">
                  <ASelect
                    v-model="item.mainDirectorId"
                    placeholder="负责人"
                    allow-search
                    allow-clear
                    @change="formEvent('mainDirectorId', item)"
                  >
                    <AOption
                      v-for="(item, index) in employeeList"
                      :key="index"
                      :label="item.employeeName"
                      :value="item.employeeId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="name" label="辅助人员">
                  <ASelect
                    v-model="item.deputyDirectorIdList"
                    placeholder="负责人"
                    allow-search
                    allow-clear
                    multiple
                    @change="formEvent('deputyDirectorIdList', item)"
                  >
                    <AOption
                      v-for="(item, index) in employeeList"
                      :key="index"
                      :label="item.employeeName"
                      :value="item.employeeId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
            </ARow>
          </ACard>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { EmployeeResItem, getEmployeeAllList } from '@renderer/api/employee'
import {
  getProcessAllList,
  HandleProductionPlanResItem,
  ProcessResItem,
  prodFlowBatchAdd,
  ProductionFinishReq,
  ProductionPlanResItem
} from '@renderer/api/productionDep'
import { useMenuState } from '@renderer/store'
import { getArrayItemType } from '@renderer/types/global'
import { uniq } from 'lodash-es'

interface Props {
  [key: string]: any
  checkData?: Partial<HandleProductionPlanResItem>[]
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return []
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<ProductionFinishReq>({
  productId: '',
  planQty: 0,
  productQty: 0,
  totalLossRate: 0,
  remark: '',
  materialQty: 0,
  detailList: [
    {
      processId: '',
      qty: 0,
      lossRate: 0,
      mainDirectorId: '',
      mainDirectorName: '',
      deputyDirectorIdList: []
    }
  ],
  prodPlanCode: ''
})
const processList = ref<ProcessResItem[]>([])
const menuParam = useMenuState()
const productPlanItem = ref<ProductionPlanResItem>() // 选中的计划单
const employeeList = ref<EmployeeResItem[]>([])
const modalLoad = ref(false)

// 获取工序
const getProcess = async () => {
  const res = await getProcessAllList({})
  processList.value = res.data.list
}
// 获取员工列表
const getEmployee = () => {
  getEmployeeAllList({}).then((res) => {
    employeeList.value = res.data.list
  })
}

// 弹窗事件
const modalEvent = async (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          modalLoad.value = true
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.prodFlowId = undefined
          }
          const apiParams = props.checkData.map((item) => {
            return {
              prodPlanId: item.prodPlanId!,
              prodPlanCode: item.prodPlanCode!,
              productId: item.productId,
              planQty: form.value.planQty,
              productQty: form.value.productQty,
              totalLossRate: form.value.totalLossRate,
              detailList: form.value.detailList,
              inbounderld: form.value.inbounderld,
              materialQty: form.value.materialQty
            }
          })
          prodFlowBatchAdd(apiParams)
            .then(() => {
              Message.success('创建生产完成记录成功')
              modalEvent('cancel')
              emit('reload')
            })
            .finally(() => {
              modalLoad.value = false
            })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        prodPlanCode: '',
        productId: '',
        planQty: 0,
        productQty: 0,
        totalLossRate: 0,
        remark: '',
        materialQty: 0,
        detailList: [
          {
            processId: '',
            qty: 0,
            lossRate: 0,
            mainDirectorId: '',
            mainDirectorName: '',
            deputyDirectorIdList: []
          }
        ]
      }
      productPlanItem.value = undefined
      emit('update:visible', false)
      break
    case 'open': {
      menuParam.switchEditStatus(true)
      await getProcess()
      getEmployee()
      const temp = uniq(props.checkData.map((item) => item.processIdList).flat())
      form.value.detailList = temp.map((item) => {
        const temp = { lossRate: 0, qty: 0, processId: item! }
        formEvent('processId', temp)
        return temp
      })

      break
    }
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        prodPlanCode: '',
        productId: '',
        planQty: 0,
        productQty: 0,
        totalLossRate: 0,
        remark: '',
        materialQty: 0,
        detailList: [
          {
            processId: '',
            qty: 0,
            lossRate: 0,
            mainDirectorId: '',
            mainDirectorName: '',
            deputyDirectorIdList: []
          }
        ]
      }
      productPlanItem.value = undefined
      emit('update:visible', false)
      break
    default:
      break
  }
}

// 表单
const formEvent = (
  type: string,
  detailItem?: getArrayItemType<ProductionFinishReq['detailList']>
) => {
  switch (type) {
    case 'processId':
      {
        const temp = processList.value.find((item) => item.processId === detailItem?.processId)
        if (temp) {
          detailItem!.mainDirectorId = temp.mainDirectorId
          detailItem!.mainDirectorName = temp.mainDirectorName
          detailItem!.deputyDirectorIdList = temp.deputyDirectorIdList
          detailItem!.deputyDirectorNameList = temp.deputyDirectorNameList
        }
      }
      break
    case 'deputyDirectorIdList':
      detailItem!.deputyDirectorNameList = employeeList.value.flatMap((item) => {
        if (detailItem?.deputyDirectorIdList?.includes(item.employeeId)) {
          return [item.employeeName]
        } else {
          return []
        }
      })
      break
    case 'mainDirectorId':
      detailItem!.mainDirectorName = employeeList.value.find(
        (item) => item.employeeId === detailItem?.mainDirectorId
      )?.employeeName
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        processId: '',
        qty: 0,
        lossRate: 0,
        mainDirectorId: '',
        mainDirectorName: '',
        deputyDirectorIdList: []
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}
</style>
